import requests
import random
import time
import hashlib

'''
i: 你
from: AUTO
to: AUTO
smartresult: dict
client: fanyideskweb
salt: 15885180943890
sign: 57e9a274061e4db42dab8719544d2890
ts: 1588518094389
bv: b286f0a34340b928819a6f64492585e8
doctype: json
version: 2.1
keyfrom: fanyi.web
action: FY_BY_CLICKBUTTION
'''

'''
t - 版本號加密  bv
r =時間戳   ts
i= r+0-9的隨機數  salt
n.md5("fanyideskweb" + e + i + "Nw(nmmbP%A-r6U3EUn]Aj")  sign
e 需要翻譯的單詞
'''


def md5_(string):
    en_str = string.encode('utf-8')
    m = hashlib.md5()
    m.update(en_str)
    str_md5 = m.hexdigest()
    return str_md5




def translate(code):
    ts = int(time.time() * 1000)
    salt = int(str(ts) + str(random.randint(0, 9)))
    text = 'fanyideskweb' + code + str(salt) + 'Nw(nmmbP%A-r6U3EUn]Aj'
    sign = md5_(text)
    ua = "5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36"
    bv = md5_(ua)
    headers = {
        'Host': 'fanyi.youdao.com',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0',
        'Accept': 'application/json, text/javascript, */*; q=0.01',
        'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
        'Accept-Encoding': 'gzip, deflate', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'X-Requested-With': 'XMLHttpRequest', 'Content-Length': '262', 'Connection': 'keep-alive',
        'Referer': 'http://fanyi.youdao.com/',
        'Cookie': 'YOUDAO_MOBILE_ACCESS_TYPE=1; OUTFOX_SEARCH_USER_ID=1378414660@10.108.160.19; JSESSIONID=aaaBTGxpwV4EQfnO_Oy1w; ___rl__test__cookies=1569154996426; OUTFOX_SEARCH_USER_ID_NCOO=752434577.0207007'
    }

    url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'

    form_data = {'i': code,
                 'from': 'AUTO',
                 'to': 'AUTO',
                 'smartresult': 'dict',
                 'client': 'fanyideskweb',
                 'salt': salt,
                 'sign': sign,
                 'ts': ts,
                 'bv': bv,
                 'doctype': 'json',
                 'version': '2.1',
                 'keyfrom': 'fanyi.web',
                 'action': 'FY_BY_REALTlME'}

    response = requests.post(url=url, data=form_data, headers=headers).json()
    return response


if __name__ == '__main__':
    string = input('请输入需要翻译的内容：')
    data = translate(string)
    ago_print = data['translateResult'][0][0]['src']
    later_print = data['translateResult'][0][0]['tgt']
    jieshi = data['smartResult']['entries']
    # 对翻译出来的解释内容进行简单处理
    explain = ''
    for i in jieshi:
        if i == '':
            pass
        else:
            i.replace('\r\n','')
            explain += i
    print('翻译前：{}\n翻译后：{}\n解释：\n{}\n'.format(ago_print, later_print, explain))